package com.devcon5.StudentPlanner;

import java.util.Calendar;

import baseclasses.Assignment;
import baseclasses.Course;
import baseclasses.Reminder;
import database.AssignmentDAO;
import database.ReminderDAO;

import forms.AssignmentForm;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class AddAssignment extends AssignmentForm {

	private AlertDialog alert;

	private boolean selected;

	//	variables save instance state in case the user leaves the application w/o pressing back button
	protected static final String COURSE_SELECTED = "COURSE_SELECTED";
	private boolean courseSeleced;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//this persists the data in case the user should leave the application if the user has entered any information that was persisted before leaving
		if(savedInstanceState != null)
		{
			timeChanged = savedInstanceState.getBoolean(TIME_CHANGED);
			courseSeleced = savedInstanceState.getBoolean(COURSE_SELECTED);
			remindInteger = savedInstanceState.getInt(REMINDER_INT);
			remindString = savedInstanceState.getString(REMINDER_STRING);
			updateReminderTextView();	//AssignmentForm's updateReminderTextView function calls to reload text onCreate (when the user returns)

			dueDateLong = savedInstanceState.getLong(DUE_DATE_LONG);
			dueDate = Calendar.getInstance();
			dueDate.setTimeInMillis(dueDateLong);
			dueDateText.setText(Assignment.getDueDateString(dueDate, "MM/dd/yyyy"));
			timeDueText.setText(Course.getStartTimeString(dueDate, "hh:mm a"));
		}
		else	//if no data was entered to be saved, on return, set the due date & time due to whichever assignment the user was viewing at the time
		{
			dueDate = Calendar.getInstance();
			dueDateText.setText(Assignment.getDueDateString(dueDate, "MM/dd/yyyy"));
			dueDate.set(Calendar.HOUR_OF_DAY, ((Course)courseSpinner.getSelectedItem()).getStartTime().get(Calendar.HOUR_OF_DAY));
			dueDate.set(Calendar.MINUTE, ((Course)courseSpinner.getSelectedItem()).getStartTime().get(Calendar.MINUTE));
			timeDueText.setText(Course.getStartTimeString(dueDate, "hh:mm a"));
		}



		//change due date time according to the selected course start time
		//this way, this will be the default due date & time for an assignment entered under a specific course
		//unless it was already set
		courseSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
		
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if(!timeChanged)
				{
					if(selected)
					{
						dueDate.set(Calendar.HOUR_OF_DAY, courses.get(arg2).getStartTime().get(Calendar.HOUR_OF_DAY));
						dueDate.set(Calendar.MINUTE, courses.get(arg2).getStartTime().get(Calendar.MINUTE));
						timeDueText.setText(Course.getStartTimeString(dueDate, "hh:mm a"));
					}
					else
						selected = true;
				}
				courseID = courses.get(arg2).getId();
			}
		
			public void onNothingSelected(AdapterView<?> arg0) {
				//------------
			}
		});


		//If there is more than one course available, present the user with a show course selection dialog
		if(courses.size()>1 && !courseSeleced){

			if(alert==null)
				alert = createCourseAlertDialog();
			alert.show();
		}
	}



	
	 //Creates and returns the "Choose Course" dialog
	public AlertDialog createCourseAlertDialog(){

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Course");
		builder.setIcon(R.drawable.check);
		CharSequence[] courseStrings = new CharSequence[courses.size()];
		for(int i=0;i<courses.size();i++){
			courseStrings[i] = courses.get(i).getName();
		}
		builder.setItems(courseStrings, new DialogInterface.OnClickListener() {

		
			public void onClick(DialogInterface dialog, int which) {
				courseSpinner.setSelection(which);
				courseSeleced = true;
			}
		});
		alert = builder.create();
		return alert;

	}


	@Override 
	protected void onSaveButtonClicked(){	//Inherited from AssignmentForm
		//Uses courseID based constructor in Assignment class
		Assignment assignment = new Assignment(courseID, assignmentNameString, descriptionString, dueDate, false);	
		long assignmentId = AssignmentDAO.addAssignment(context, assignment);	//the ID is returned as a result of adding the assignment to the DB

		if(assignmentId==-1){	//If -1 flag is returned, it didn't go through
			Toast.makeText(context, "Error adding assignment", Toast.LENGTH_SHORT).show();
		}
		else{
			if(reminderToggleButton.isChecked()){	//if the reminder button is also checked, create a new reminder, register it w/ AlarmManager
				Reminder reminder = new Reminder((int)assignmentId, remindInteger, remindString);
				if(ReminderDAO.addReminder(context, reminder)!=-1){
					AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
					reminder.createAlarm(context, dueDate, am);
					
				}
			}
			
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState){ 	//activity displaced or orientation changed

		outState.putBoolean(COURSE_SELECTED, courseSeleced);
		outState.putLong(DUE_DATE_LONG, dueDate.getTimeInMillis());
		outState.putInt(REMINDER_INT, remindInteger);
		outState.putString(REMINDER_STRING, remindString);
		outState.putBoolean(TIME_CHANGED, timeChanged);

		super.onSaveInstanceState(outState);

	}


	@Override
	protected void onPause() {	//alert dialog, dismiss it onPause
		if(alert!=null)
			alert.dismiss();
		super.onPause();
	}
}
